#!/bin/bash

# APS数据备份脚本
# 用于定期备份MySQL和Redis数据

set -e

# 配置
BACKUP_DIR="/backup/aps"
RETENTION_DAYS=7
DATE=$(date +%Y%m%d_%H%M%S)

# 颜色定义
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${YELLOW}开始备份APS数据...${NC}"

# 创建备份目录
mkdir -p ${BACKUP_DIR}

# 备份MySQL
echo -e "${GREEN}备份MySQL数据库...${NC}"
docker exec aps-mysql mysqldump \
  -uroot \
  -p${MYSQL_ROOT_PASSWORD:-Jsyshiyou@0723} \
  --single-transaction \
  --quick \
  --lock-tables=false \
  ${MYSQL_DATABASE:-aps_example} \
  | gzip > ${BACKUP_DIR}/mysql_${DATE}.sql.gz

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ MySQL备份成功: mysql_${DATE}.sql.gz${NC}"
else
    echo -e "${RED}✗ MySQL备份失败${NC}"
    exit 1
fi

# 备份Redis
echo -e "${GREEN}备份Redis数据...${NC}"
docker exec aps-redis redis-cli -a ${REDIS_PASSWORD:-123456} BGSAVE > /dev/null 2>&1
sleep 2
docker cp aps-redis:/data/dump.rdb ${BACKUP_DIR}/redis_${DATE}.rdb

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Redis备份成功: redis_${DATE}.rdb${NC}"
else
    echo -e "${RED}✗ Redis备份失败${NC}"
fi

# 备份配置文件
echo -e "${GREEN}备份配置文件...${NC}"
tar -czf ${BACKUP_DIR}/config_${DATE}.tar.gz \
  .env \
  docker-compose.yml \
  nginx/nginx.conf \
  2>/dev/null || true

# 清理过期备份
echo -e "${GREEN}清理${RETENTION_DAYS}天前的备份...${NC}"
find ${BACKUP_DIR} -type f -mtime +${RETENTION_DAYS} -delete

# 显示备份大小
echo -e "${GREEN}当前备份文件:${NC}"
ls -lh ${BACKUP_DIR}/*${DATE}*

echo -e "${GREEN}备份完成！${NC}"

